package com.cykj.service.Impl;

import com.cykj.dto.ResponseDto;
import com.cykj.mapper.MenuMapper;
import com.cykj.mapper.PermissionMapper;
import com.cykj.pojo.PsMenu;
import com.cykj.pojo.PsPermission;
import com.cykj.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: Psychology
 * @BelongsPackage: com.cykj.service.Impl
 * @Author: 小林
 * @CreateTime: 2025-01-17 15:37
 * @Description: 菜单表service层
 * @Version: 1.0
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper mapper;
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 根据角色id获取全部菜单
     * @param roleId
     * @return
     */
    @Override
    public ResponseDto getAll(Long roleId) {
        List<PsMenu> all = mapper.getAll();
        List<PsMenu> menuData = new ArrayList<>();
        for (PsMenu data : all) {
            if (data.getMenuParentId() == 0 & permissionMapper.queryPermission(roleId, data.getMenuId()) != null) {

                menuData.add(findChildren(data, all,roleId));
            }
        }
        return menuData == null ? ResponseDto.error("查询失败") : ResponseDto.success(menuData);
    }

    /**
     * 遍历出子菜单添加到主菜单里面
     * @param nowMenu
     * @param data
     * @param roleId
     * @return
     */
    public PsMenu findChildren(PsMenu nowMenu, List<PsMenu> data, Long roleId) {
        for (PsMenu datum : data) {
            if (datum.getMenuParentId() == nowMenu.getMenuId() && permissionMapper.queryPermission(roleId, datum.getMenuId()) != null) {
                nowMenu.getChildren().add(findChildren(datum, data,roleId));
            }
        }
        return nowMenu;
    }
}

